using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Decav.Gatsb.Mobile
{
    /// <summary>
    /// An attachment to an <see cref="MmsMessage"/>.
    /// </summary>
    [Serializable]
    public class FileAttachment
    {
        /// <summary>
        /// Initializes a new <see cref="FileAttachment"/>.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="type">The content type of the file.</param>
        /// <param name="fileBytes">The bytes of the file to write.</param>
        public FileAttachment(string fileName, ContentType type, Byte[] fileBytes)
        {
            if (fileBytes == null)
                throw new ArgumentNullException("fileBytes");

            if (fileName == null)
                throw new ArgumentNullException("fileName");

            if (type == null)
                throw new ArgumentNullException("type");

            _type = type;
            _fileName = fileName;
            _fileBytes = fileBytes;
        }

        private ContentType _type;
        private Byte[] _fileBytes;
        private string _fileName;

        /// <summary>
        /// Gets the type of the content that the attachment is in.
        /// </summary>
        public ContentType Type
        {
            get
            {
                return _type;
            }
        }

        /// <summary>
        /// Gets the file name of the file.
        /// </summary>
        public string FileName
        {
            get
            {
                return _fileName;
            }
        }

        /// <summary>
        /// Saves the attachment into a file.
        /// </summary>
        /// <param name="fileName">The file to save.</param>
        public void Save(string fileName)
        {
            if (fileName == null)
                throw new ArgumentNullException("fileName");

            File.WriteAllBytes(fileName, _fileBytes);
        }

        /// <summary>
        /// Gets the text string of the content.
        /// </summary>
        /// <returns>The content as a string.</returns>
        public string ToText()
        {
            if (_type.Type != ContentType.PlainText.Type)
                throw new InvalidOperationException("Cannot convert the FileAttachment to text when it is not a text string.");

            return Encoding.Default.GetString(_fileBytes);
        }

        /// <summary>
        /// Returns the attachment name.
        /// </summary>
        /// <returns>The name of the atachment.</returns>
        public override string ToString()
        {
            return FileName;
        }
    }
}
